package com.icangya.DAO.impl;

import com.icangya.DAO.IBaseDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate5.HibernateTemplate;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by cangya4 on 2017/4/24.
 */
public class BaseDAO<T> implements IBaseDAO<T> {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private Class<T> entityClass;

    @Autowired
    private HibernateTemplate hibernateTemplate;

    public BaseDAO() {
        init();
    }

    public T get(Serializable id) {
        return (T) getHibernateTemplate().get(entityClass, id);
    }

    public List<T> list() {
        return getHibernateTemplate().loadAll(entityClass);
    }

    public Serializable save(T entity) {
        logger.info("save: " + entity.toString());
        getHibernateTemplate().clear();
        Serializable id = getHibernateTemplate().save(entity);
        getHibernateTemplate().flush();
        return id;
    }

    public boolean update(T entity) {
//        logger.info("update: " + entity.toString());
        try {
            getHibernateTemplate().clear();
            getHibernateTemplate().update(entity);
            getHibernateTemplate().flush();
            return true;
        } catch (DataAccessException e) {
            logger.error("更新失败" + e.getMessage());
        }
        return false;
    }

    public void remove(T entity) {
        logger.info("remove: " + entity.toString());
        getHibernateTemplate().delete(entity);
    }


    protected HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }

    private void init() {
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        entityClass = (Class) params[0];
    }
}
